﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using VehicleManagement.Codes;
using System.Text;
using System.IO;

namespace VehicleManagement.Controllers
{
    [CustomerAuthorize(Roles = "管理员")]
    public class UtilityController : Controller
    {
        //
        // GET: /Utility/

        public ActionResult Index()
        {
            return View();
        }

        //
        // POST: /Utility/GetBackupFileList
        [HttpPost, ActionName("GetBackupFileList")]
        public ActionResult GetBackupFileList()
        {
            char[] spliter = new Char[]{' '};
            string[] files = Directory.GetFiles(Server.MapPath("\\backup"));
            List<Object> list = new List<Object>();
            foreach (string s in files)
            {
                if (s.ToLower().EndsWith(".bak"))
                {
                    FileInfo fileInfo = new FileInfo(s);
                    string[] fileNameArray = fileInfo.Name.Split(spliter, 3);
                    list.Add(new { File = fileInfo.Name, Time = fileNameArray[0] +" "+ fileNameArray[1], Backupname = fileNameArray[2] });
                }
            }
            return Json(list);
        }

        //
        // POST: /Utility/Backup
        [HttpPost, ActionName("Backup")]
        public ActionResult Backup(string backupname)
        {
            string connString = SqlMapperManager.Instance.Get().DataSource.ConnectionString;
            if (backupname.Contains(' '))
            {
                backupname = backupname.Replace(' ', '_');
            }
            StringBuilder sb = new StringBuilder();
            sb.Append(Server.MapPath("\\backup"));
            sb.Append("\\");
            string time = DateTime.Now.ToString("yyyy-MM-dd HH：MM：ss");
            string fileName = string.Format("{0} {1}", time, backupname);
            sb.Append(fileName);
            sb.Append(".bak");
            using (SqlConnection connection = new SqlConnection(connString))
            {
                connection.Open();
                SqlCommand dataCommand = new SqlCommand();
                dataCommand.Connection = connection;
                dataCommand.CommandType = CommandType.Text;
                dataCommand.CommandText = string.Format(@"BACKUP DATABASE 
                    VehicleManagement TO DISK= '{0}'", sb.ToString());
                try
                {
                    dataCommand.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "false", Message = ex.Message});
                }
            }
            return Json(new { Result = "true", Message = "数据库备份成功!", File = fileName + ".bak", Time = time, Backupname = backupname + ".bak" });
        }

        //
        // POST: /Utility/Delete
        [HttpPost, ActionName("Delete")]
        public ActionResult Delete(string file)
        {
            JsonResult result = new JsonResult();
            StringBuilder sb = new StringBuilder();
            sb.Append(Server.MapPath("\\backup"));
            sb.Append("\\");
            sb.Append(file);
            try
            {
                System.IO.File.Delete(sb.ToString());
                result.Data = new { Result = "true", Message = "备份文件已经成功删除!" };
            }
            catch (Exception e)
            {
                result.Data = new { Result = "false", Message = e.Message };
            }
            return result;
        }

        //
        // POST: /Utility/Restore
        [HttpPost, ActionName("Restore")]
        public ActionResult Restore(string file)
        {
            string connString = SqlMapperManager.Instance.Get().DataSource.ConnectionString;
            StringBuilder sb = new StringBuilder();
            sb.Append(Server.MapPath("\\backup"));
            sb.Append("\\");
            sb.Append(file);

            using (SqlConnection connection = new SqlConnection(connString))
            {
                connection.Open();

                SqlCommand dataCommand = new SqlCommand();
                dataCommand.Connection = connection;
                dataCommand.CommandType = CommandType.Text;
                try
                {
                    dataCommand.CommandText = string.Format(@"USE master;
                        ALTER DATABASE VehicleManagement 
                        SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
                        RESTORE DATABASE VehicleManagement
                        FROM DISK='{0}' WITH REPLACE", sb.ToString());
                    dataCommand.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "false", Message = ex.Message });
                }
            }
            return Json(new { Result = "true", Message = "数据库还原成功!" });
        }
    }
}
